package com.mycompany.webapp.action;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.appfuse.webapp.action.BaseAction;

public class DemoForNoExtendJson extends BaseAction {
	/** 	 */
	private static final long serialVersionUID = 1L;
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	} 

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String execute() throws Exception {
		HttpServletRequest request = getRequest();
		HttpServletResponse response = getResponse();
//		JSONObject jsonObject = readJson(request);
//		String[] fields = { "name","age" };
//		autoSetValue(fields, this, jsonObject);
		print(response, "{\"name\":"+name+",\"age\":"+age+"}");
//		return null;
		 return this.SUCCESS;
	}
 
	public void autoSetValue(String[] strFields, Object obj, JSONObject jsonObj) {
		Class clazz = obj.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for (int i = 0; i < strFields.length; i++) {
			String fieldName = strFields[i];
			Field field = null;
			for (int j = 0; j < fields.length; j++) {
				if (fields[j].getName().equals(fieldName)) {
					field = fields[j];
					break;
				}
			}
			System.out.println("====fieldName==="+fieldName);
			System.out.println("===obj===="+obj);
			
			String value = (String)jsonObj.get(fieldName);
			try {
			if (field.getType().equals(int.class)) {
			    field.setInt(obj, Integer.parseInt( value));
			   } else if (field.getType().equals(long.class)) {
			    field.setLong(obj, Long.parseLong(value));
			   } else if (field.getType().equals(String.class)) {
			    field.set(obj, value);
			   } else if (field.getType().equals(double.class)) {
			    field.setDouble(obj, Double.parseDouble(value));
			   } else if (field.getType().equals(float.class)) {
			    field.setFloat(obj, Float.parseFloat(value));
			   } else if (field.getType().equals(java.util.Date.class)) {
//			    field.set(obj, new java.util.Date(iValue));
			   } else if (field.getType().equals(Long.class)) {
			    field.set(obj, new Long(value));
			   } else if (field.getType().equals(Integer.class)) {
			    field.set(obj, new Integer(value));
			   } else if (field.getType().equals(Double.class)) {
			    field.set(obj, new Double(value));
			   } else if (field.getType().equals(Float.class)) {
			    field.set(obj, new Float(value));
			   }
			
				 
			} catch (Exception e) {
				e.printStackTrace();
			}

		}
	}

	/** ===============copy from springside3 ================ */
	/**
	 * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
	 */
	public static void setFieldValue(final Object object,
			final String fieldName, final Object value) {
		Field field = getDeclaredField(object, fieldName);
		if (field == null) {
			throw new IllegalArgumentException("Could not find field ["	+ fieldName + "] on target [" + object + "]");
		}
		makeAccessible(field);

		try {
			field.set(object, value);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
	 */
	public static Object getFieldValue(final Object object,	final String fieldName) {
		Field field = getDeclaredField(object, fieldName);
		if (field == null) {
			throw new IllegalArgumentException("Could not find field ["	+ fieldName + "] on target [" + object + "]");
		}

		makeAccessible(field);

		Object result = null;
		try {
			result = field.get(object);
		} catch (IllegalAccessException e) {
		}
		return result;
	}

	/**
	 * 循环向上转型, 获取对象的DeclaredField.
	 * 
	 * 如向上转型到Object仍无法找到, 返回null.
	 */
	protected static Field getDeclaredField(final Object object,final String fieldName) {
		for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
			try {
				return superClass.getDeclaredField(fieldName);
			} catch (NoSuchFieldException e) {
				// Field不在当前类定义,继续向上转型
			}
		}
		return null;
	}

	protected static void makeAccessible(final Field field) {
		if (!Modifier.isPublic(field.getModifiers())
				|| !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
			field.setAccessible(true);
		}
	}

	/**
	 * 读取请求参数转换JSONObject对象
	 * 
	 * @param request
	 *            HttpServletRequest 对象
	 * @return json格式的String对象
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	protected JSONObject readJson(HttpServletRequest request) throws Exception {
		JSONObject jsonObject = new JSONObject();
		try {
			Map parameterMap = request.getParameterMap();
			// 通过循环遍历的方式获得key和value并set到JSONObject中
			Iterator paIter = parameterMap.keySet().iterator();
			while (paIter.hasNext()) {
				String key = paIter.next().toString();
				String[] values = (String[]) parameterMap.get(key);
				jsonObject.accumulate(key, values[0]);
			}
			log.info("从客户端获得json=" + jsonObject.toString());
		} catch (Exception e) {
			log.error("获取json数据出错，错误信息如下：nt" + e.getMessage());
			e.printStackTrace();
			throw e;
		}
		return jsonObject;
	}

	protected void print(HttpServletResponse response, String info)	throws IOException {
		try {
			response.getWriter().print(info);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}
}
